from django.core.validators import RegexValidator
from django.shortcuts import render
from django.http import HttpResponse
from django import forms
from app01 import models
import random
import redis
from django_redis import get_redis_connection
import json
from utils.alicloud.sms import send_sms
from django.conf import settings
# Create your views here.


# conn = redis.Redis(host='192.168.31.103', port=6379, password='123456', encoding='utf-8')

# 使用连接池连接redis
# pool = redis.ConnectionPool(host='192.168.31.103', port=6379, password='123456', encoding='utf-8', max_connections=1000)
# conn = redis.Redis(connection_pool=pool)

# 使用django_redis连接
conn = get_redis_connection('default')


class RegisterModelForm(forms.ModelForm):

    mobile_phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^1[3-9]\d{9}', '手机号格式错误')])
    password = forms.CharField(label='密码', widget=forms.PasswordInput())
    confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput())
    code = forms.CharField(label='验证码')

    class Meta:
        model = models.UserInfo
        fields = ['uesrname', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入' + field.label


def register(request):
    form = RegisterModelForm()
    return render(request, 'app01/register.html', {'form': form})


def send_check_code(request):
    template = request.GET.get('template')
    template_code = settings.TEMPLATE_CODE.get(template)
    if not template_code:
        return HttpResponse('模板不存在')
    # template_code = 'SMS_154950909'  # 测试专用
    check_code = random.randrange(100000, 999999)
    result = send_sms('18844383906', settings.SIGN_NAME, template_code, "{'code': '" + str(check_code) + "'}")
    result = json.loads(str(result, encoding='utf-8'))
    print(result)
    if result['Code'] == 'OK':
        return HttpResponse('成功')
    else:
        return HttpResponse(result['Message'])
